﻿using System;
using System.Diagnostics;
using System.ServiceProcess;

namespace SimpleServiceBus.EndpointMonitorService
{
    public partial class EndpointMonitorWinService : ServiceBase
    {
        private readonly EndpointMonitorServerHost serverHost = new EndpointMonitorServerHost();

        public EndpointMonitorWinService()
        {
            InitializeComponent();
            ServiceName = "SimpleServiceBus.EndpointMonitor";
        }

        protected override void OnStart(string[] args)
        {
            if (StartServer())
                EventLog.WriteEntry(ServiceName + " started successfully!", EventLogEntryType.Information);
            else
            {
                EventLog.WriteEntry(ServiceName + " failed to start!", EventLogEntryType.Error);
                Stop();
            }
        }

        protected override void OnStop()
        {
            if (StopServer())
                EventLog.WriteEntry(ServiceName + " stopped.", EventLogEntryType.Information);
            else
                EventLog.WriteEntry(ServiceName + " failed to stop.", EventLogEntryType.Error);
        }

        private bool StartServer()
        {
            if (!serverHost.IsRunning)
            {
                try
                {
                    serverHost.Start();
                }
                catch (Exception ex)
                {
                    EventLog.WriteEntry(String.Format("Exception thrown when trying to start {1}: {0}", ex.Message,ServiceName), EventLogEntryType.Error);
                    EventLog.WriteEntry(String.Format("     StackTrace: {0}", ex.StackTrace), EventLogEntryType.Warning);
                }
            }
            return serverHost.IsRunning;
        }

        private bool StopServer()
        {
            if (serverHost.IsRunning)
            {
                try
                {
                    serverHost.Stop();
                }
                catch (Exception ex)
                {
                    EventLog.WriteEntry(String.Format("Exception thrown when trying to shutdown {1}: {0}", ex.Message,ServiceName), EventLogEntryType.Error);
                    EventLog.WriteEntry(String.Format("     StackTrace: {0}", ex.StackTrace), EventLogEntryType.Warning);
                }
            }
            return (!serverHost.IsRunning);
        }
    }
}
